package com.heima.wemedia.service.Impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants.WemediaConstants;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.treadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsMaterial;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}")
    String webSite;

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 查询所有自媒体文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //构建查询条件
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaQuery();

        //如果文章标题按照文章标题模糊查询
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            wrapper.like(WmNews::getTitle, dto.getKeyword());
        }

        //如果有频道信息,按照ID查询
        wrapper.eq((dto.getChannelId() != null), WmNews::getChannelId, dto.getChannelId());

        //如果文章有状态，按照状态信息进行查询
        wrapper.eq((dto.getStatus() != null), WmNews::getStatus, dto.getStatus());

        //如果有开始时间
        if ((dto.getBeginPubDate() != null) && (dto.getEndPubDate() != null)) {
            wrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }

        //获取用户
        WmUser user = WmThreadLocalUtils.getUser();
        if (user != null) {
            wrapper.eq(WmNews::getUserId, user.getId());
        }

        wrapper.orderByDesc(WmNews::getCreatedTime);

        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());

        IPage<WmNews> result = page(page, wrapper);

        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), result.getTotal()
                , result.getRecords());
        responseResult.setHost(webSite);
        return responseResult;
    }

    //上下架

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //1.检查参数
        if (dto == null || dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if (enable == null ||
                (!WemediaConstants.WM_NEWS_UP.equals(enable) && !WemediaConstants.WM_NEWS_DOWN.equals(enable))) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "上下架状态错误");
        }

        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        //3.判断文章是否发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章不是发布状态，不能上下架");
        }
        //4.修改文章状态，同步到app端（后期做）TODO
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId())
                .set(WmNews::getEnable, dto.getEnable()));

        //2021/11/25 发布消息上下架
        //判断articleId是否为空
        if (wmNews.getArticleId() !=null ){
           if (enable.equals(WemediaConstants.WM_NEWS_UP)){
                //上架
               rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE
                        , NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY, wmNews.getId());
               log.info("消息上架发送 成功");
            }else {
               //下架
               rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE
                       , NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY, wmNews.getId());
               log.info("消息下架发送 成功");
           }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    @Autowired
    WmNewsMapper wmNewsMapper;

    @Override
    public ResponseResult queryList(NewsAuthDTO dto) {

        //1.检查参数
        dto.checkParam();
        //记录当前页
        int currentPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage() - 1) * dto.getSize());
        if (StringUtils.isNotBlank(dto.getTitle())) {
            dto.setTitle("%" + dto.getTitle() + "%");
        }

        //2.分页查询
        List<WmNewsVO> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        long count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, wmNewsVoList);
        result.setHost(webSite);
        return result;

    }




    @Autowired
    WmUserMapper wmUserMapper;


    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if(wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //4.封装vo信息返回
        WmNewsVO wmNewsVo = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }


    /**
     * 自媒体文章人工审核
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //1.参数检查
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 检查文章状态 不能为9  已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布");
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);




        // TODO 通知定时发布文章
        if (status.shortValue() == WmNews.Status.ADMIN_SUCCESS.getCode()){
            //延时队列 .发送消息
            long publishTime = wmNews.getPublishTime().getTime();
            long nowTime = System.currentTimeMillis();//当前时间
            long remainTime = (publishTime - nowTime);

            //发送消息
            rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                    , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY, wmNews.getId()
                    //设置延迟属性第四个参数
                    , new MessagePostProcessor() {
                        @Override
                        public Message postProcessMessage(Message message) throws AmqpException {

                            //对消息做后置处理,设置消息头 x-delay
                            message.getMessageProperties().setHeader("x-delay", remainTime <= 0 ? 0 : remainTime);
                            return message;
                        }
                    }
            );
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }






    //删除
    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章Id不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已发布，不能删除");
        }
        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult();
    }


    //根据Id查询
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1 参数检查
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }


    @Transactional
    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        //1.1检验参数
        if (StringUtils.isBlank(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章内容不能为空");
        }
        //判断登陆
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "请登录");
        }
        //1.2封装数据到WmNews
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //1.3设置Type为空
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);//防止爆异常
        }
        //1.4 news的封面  images 数据库里存的是字符串，但是前端
        //传入数据的dto    images字段是字符串集合
        if (!CollectionUtils.isEmpty(dto.getImages())) {
            String imagesStr = imagesToString(dto.getImages());
            wmNews.setImages(imagesStr);
        }
        //1.5 设置UserId
        wmNews.setUserId(user.getId());

        //2.1 保存或者修改
        saveOrUpdateWmNews(wmNews);

        //3.0如果是草稿我们就不用保存修改关系
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(dto.getStatus())) {
            return ResponseResult.okResult();
        }
        //3.1保存文章内容和素材的关联
        //3.1.1抽取文章内容中的所有图片的集合
        List<String> contentImages = ParseContentImages(dto.getContent());

        //3.2保存内容和素材的关系
        if (!CollectionUtils.isEmpty(contentImages)) {
            saveRelationInfo(contentImages, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
        }


        //3.3保存封面和素材的关联关系
        saveRelationInfoForCover(contentImages, wmNews, dto);


        //发送消息：消息的内容是文章的Id
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE, wmNews.getId());

        System.out.println("发送消息成功");


        return ResponseResult.okResult();


    }


    //3.3方法实现，保存封面和素材的关联关系
    private void saveRelationInfoForCover(List<String> contentImages, WmNews wmNews, WmNewsDTO dto) {
        //前端传递过来的封面图片
        List<String> images = dto.getImages();
        //判断type的值是否等于-1
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            //需要自动生成封面
            if (contentImages.isEmpty()) {//如果没有内容封面设置为无封面
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            } else if (contentImages.size() > 0 && contentImages.size() <= 2) {//单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = contentImages.stream().limit(1).collect(Collectors.toList());
            } else {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);//多图
                images = contentImages.stream().limit(3).collect(Collectors.toList());
                //将信息保存到wmnews里面
            }
            //如果无图就是空的
            if (!CollectionUtils.isEmpty(images)) {
                wmNews.setImages(imagesToString(images));
            }
            //更新内容到数据库的news表
            updateById(wmNews);
        }

        //替换前缀,如果封面是前端传递过来的就是有前缀的。。。
        if (!CollectionUtils.isEmpty(images)) {
            images = images.stream().map(url -> url.replaceAll(webSite, "")).distinct()
                    .collect(Collectors.toList());
            saveRelationInfo(images, wmNews.getId(), WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }


    @Autowired
    WmMaterialMapper wmMaterialMapper;

    //3.2保存内容和素材的关系
    private void saveRelationInfo(List<String> urls, Integer newId, Short type) {
//        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
//                .eq(WmMaterial::getId, WmThreadLocalUtils.getUser().getId())
//                .in(WmMaterial::getUrl, urls));
//        List<Integer> collect = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
        // 3.2.1得到素材的IDs
        List<Integer> ids = wmMaterialMapper.selectRelationsIds(urls, WmThreadLocalUtils.getUser().getId());
        //3.2.2判断素材Id是否小于路径的数量,如果小于，说明素材丢失，直接抛出异常
        if (CollectionUtils.isEmpty(ids) || ids.size() < urls.size()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "相关素材不存，保存失败");
        }
        //3.2.3保存素材和文章的关联关系
//        for (Integer id : ids) {
//            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
//            wmNewsMaterial.setMaterialId(id);
//            wmNewsMaterial.setNewsId(newId);
//            wmNewsMaterial.setType(type);
//            wmNewsMaterial.setOrd((short)0);
//            wmNewsMaterialMapper.insert(wmNewsMaterial);
//        }
        wmNewsMaterialMapper.saveRelations(ids, newId, type);
    }


    //3.1.1
    //抽取文章内容中的路径方法
    //将String = [{type:"text" , value:文本} , {type:"images" , value: "前缀+路径"}]
    //解析成为List<map>
    //<map>里面就<key:text/images  , value : 文本/前缀+路径>
    //去重
    //最后还要去前缀
    private List<String> ParseContentImages(String content) {
        //转换
        List<Map> contentMap = JSONArray.parseArray(content, Map.class);

        return contentMap.stream()
                //找到type为imgae的数据
                .filter(map -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(map.get("type")))
                //通过map找到value
                .map(o -> (String) o.get("value"))//得到图片url路径带前缀
                .map(url -> url.replaceAll(webSite, ""))//替换前缀路径
                .distinct() //去除重复路径
                .collect(Collectors.toList());
    }


    //2.1
    //保存或者修改信息到News表中
    private void saveOrUpdateWmNews(WmNews wmNews) {
        //2.2 补全WmNews信息
        //上下架
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        //上架时间
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());

        //2.3如果ID为空，就是在保存数据，直接保存  else不为空就修改
        if (wmNews.getId() == null) {
            save(wmNews);
        } else {//修改
            //先删除存在关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getId, wmNews.getId()));
            //修改
            updateById(wmNews);
        }
    }


    //1.4
    //imgaes 字符串集合转字符串方法
    private String imagesToString(List<String> images) {
        return images.stream()
                .map(url -> url.replaceAll(webSite, ""))
                .collect(Collectors.joining(","));
    }
}